package rollingCounter

//Bucket container of float64 items
type Bucket struct {
	Points []float64
	Count int
	next *Bucket
}

//Add adds the val of offset Point
func (b *Bucket)Add(offset int, val float64) {
	b.Points[offset] += val
	b.Count++
}

func (b *Bucket)Append(val float64) {
	b.Points = append(b.Points, val)
	b.Count++
}

//Reset clears the Bucket
func (b *Bucket)Reset() {
	b.Points = b.Points[:0]
	b.Count= 0
}

//Next gets the next Bucket
func (b *Bucket)Next() *Bucket {
	return b.next
}

//Window container of Buckets
type Window struct {
	buckets []Bucket
	size int
}

//type windowOption struct {
//	size int
//}
//
////Option func that sets optional parameter of window
//type Option func(opts *windowOption)
//
////WithSize return a func to set window size parameter
//func WithSize(size int) Option {
//	return func(opts *windowOption) {
//		opts.size = size
//	}
//}

//NewWindow creates a window
func NewWindow(size int) *Window {
	w := &Window{buckets: make([]Bucket, size), size: size}
	for i := 1; i <= w.size; i++ {
		w.buckets[i-1] = Bucket{Points: make([]float64, 0)}
		if i != w.size {
			w.buckets[i-1].next = &w.buckets[i]
		} else {
			w.buckets[i-1].next = &w.buckets[0]
		}
	}

	return w
}

//ResetWindow clears all the buckets in it
func (w *Window)ResetWindow() {
	for k := range w.buckets {
		w.buckets[k].Reset()
	}
}

//ResetBucket cleans up the specified bucket
func (w *Window)ResetBucket(offset int) {
	w.buckets[offset].Reset()
}

//Add adds the point of specified bucket
func (w *Window)Add(offset int, val float64) {
	if len(w.buckets[offset].Points) == 0 {
		w.buckets[offset].Append(val)
		return
	}
	w.buckets[offset].Add(0, val)
}

//Append appends val to points of specified bucket
func (w *Window)Append(offset int, val float64) {
	w.buckets[offset].Append(val)
}

//Size returns the size of window
func (w *Window)Size() int {
	return w.size
}

//Iterator generates an iterator
func (w *Window)Iterator(count int, offset int) Iterator {
	return Iterator{count: count, cur: &w.buckets[offset]}
}
